package com.ctgu.module.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctgu.common.util.ResultUtil;
import com.ctgu.module.admin.model.Email;
import com.ctgu.module.admin.model.Mailbox;
import com.ctgu.module.admin.model.User;
import com.ctgu.module.admin.service.EmailService;
import com.ctgu.module.admin.service.MailboxService;
import com.ctgu.module.admin.vo.base.ResponseVo;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;


@Controller
@AllArgsConstructor
@RequestMapping("/mailbox")
public class MailboxController {
    private final EmailService emailService;
    private final MailboxService mailboxService;

    public List<Email> getAllEmail(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user==null)
            return null;
        QueryWrapper<Mailbox> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user.getUserId());
        Mailbox mailbox = mailboxService.getOne(wrapper);
        if(mailbox==null || mailbox.getCode()==null)
            return null;
        return emailService.selectAllEmailsByAddress(mailbox.getEmailAddress());
    }

    @PostMapping("/emailInfo_count")
    @ResponseBody
    public Map<String, Integer> getEmailInfo_count(){
        Map<String, Integer> map = new HashMap<>();
        List<Email> email_list = getAllEmail();
        if(email_list==null)
            return null;
        int receive = email_list.size();    //获取接收邮件数量

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user==null)
            return null;
        QueryWrapper<Email> wrapper = new QueryWrapper<>();
        wrapper.eq("post_address", user.getEmail());
        wrapper.eq("mark", 2);
        List<Email> list = emailService.list(wrapper);
        int send = list.size();     //获取发送邮件数量

        map.put("receive",receive);
        map.put("send",send);
        return map;
    }

    @PostMapping("/emailInfoIn_30day")
    @ResponseBody
    public Map<String, Integer[]> getEmailInfoIn_30days(){
        Map<String, Integer[]> map = new HashMap<>();
        Integer[] spam = new Integer[30];
        Integer[] norm = new Integer[30];
        for(int i=0;i<30;i++){
            spam[i]=0;
            norm[i]=0;
        }
        List<Email> email_list = getAllEmail();
        if(email_list==null)
            return null;
        LocalDateTime now = LocalDateTime.now();
        int today = now.getDayOfYear();
        for (Email email:email_list) {
            int day_pass = today-email.getCreateTime().getDayOfYear();//获取当前邮件距离今天已经过去了多少天
            if(day_pass>=30)
                continue;
//            System.out.println(day_pass);
            if(email.getMark()==1)
                spam[day_pass]++;
            else if(email.getMark()==0)
                norm[day_pass]++;
        }
        map.put("spam",spam);
        map.put("norm",norm);
        return map;
    }

    @GetMapping("/receiveNewEmail")
    @ResponseBody
    public List<Email> showNewEmail(Model model){
        List<Email> email_list = getAllEmail();
        if(email_list==null)
            return null;
        email_list.removeIf(email -> email.getStatus() != 0);   // 0表示这是一个从未提示过的新邮件
        //只保留状态为0的邮件，然后返回
        model.addAttribute("newEmailList",email_list);

        //光返回还不行，还得将status状态设置为 1, 一旦设置为 1， 下一次不会在右下角弹窗
        for(Email email:email_list){
            QueryWrapper<Email> wrapper = new QueryWrapper<>();
            wrapper.eq("id",email.getId());
            email.setStatus(1);
            emailService.update(email, wrapper);
        }

        if(email_list.size()>=1){
//            System.out.println("准备返回邮件");
            return email_list;
        }else{
            return null;
        }
    }

    @PostMapping("/deleteOne")
    @ResponseBody
    public ResponseVo deleteOneEmailByID(Integer email_id){
//        System.out.println("准备删除的邮件ID="+email_id);
        QueryWrapper<Email> wrapper = new QueryWrapper<>();
        wrapper.eq("id",email_id);
        Email email = emailService.getOne(wrapper);
        if(email!=null)
            email.setStatus(-1);
            emailService.update(email,wrapper);
//        emailService.removeById(email_id);    //这是真删除
//        return "删除邮件：+" + email_id + "成功";
        return ResultUtil.success("删除邮件成功");
    }


    /**
     * 接收邮件的部分
     */
    @GetMapping("/normal")
    public String normalEmails(Model model) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<Email> email_list = getAllEmail();
        if(email_list==null)
            return "redirect:/attachment/email-setting";

        int numOfNormal = 0, numOfSpam = 0, numOfSend = 0;
        List<Email> list = new ArrayList<>();

        for(Email email : email_list){
            if(email.getStatus() == -1){
                continue;
            }
            if(email.getMark() == 0){
                numOfNormal++;
                list.add(email);
            }else if(email.getMark() == 1){
                numOfSpam++;
            }
        }
        QueryWrapper<Email> wrapper = new QueryWrapper<>();
        wrapper.eq("post_address", user.getEmail());
        wrapper.eq("status", 1);
        wrapper.eq("mark", 2);
        List<Email> sendList = emailService.list(wrapper);
        numOfSend = sendList.size();

//        int all = email_list.size();
//        // 将邮件List中，已被标记成垃圾邮件的邮件剔除
//        email_list.removeIf(email -> email.getMark() == 1);
//
//        model.addAttribute("email_list",email_list);
//        int numOfNormal = email_list.size();
//        int numOfSpam = all - numOfNormal;
        model.addAttribute("email_list",list);
        model.addAttribute("hamNum",numOfNormal);
        model.addAttribute("spamNum",numOfSpam);
        model.addAttribute("sendNum",numOfSend);

        return "/admin/email/list";
    }
    /**
     * 显示垃圾邮件
     */
    @GetMapping("/spam")
    public String spamEmails(Model model){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<Email> email_list = getAllEmail();
        if(email_list==null)
            return "/admin/upload/email-api";
        int numOfNormal = 0, numOfSpam = 0, numOfSend = 0;
        List<Email> list = new ArrayList<>();

        for(Email email : email_list){
            if(email.getStatus() == -1){
                continue;
            }
            if(email.getMark() == 0){
                numOfNormal++;
            }else if(email.getMark() == 1){
                numOfSpam++;
                list.add(email);
            }
        }
        QueryWrapper<Email> wrapper = new QueryWrapper<>();
        wrapper.eq("post_address", user.getEmail());
        wrapper.eq("status", 1);
        wrapper.eq("mark", 2);
        List<Email> sendList = emailService.list(wrapper);
        numOfSend = sendList.size();

//        int all = email_list.size();
//        // 将邮件List中，已被标记成垃圾邮件的邮件剔除
//        email_list.removeIf(email -> email.getMark() == 1);
//
//        model.addAttribute("email_list",email_list);
//        int numOfNormal = email_list.size();
//        int numOfSpam = all - numOfNormal;
        model.addAttribute("email_list",list);
        model.addAttribute("hamNum",numOfNormal);
        model.addAttribute("spamNum",numOfSpam);
        model.addAttribute("sendNum",numOfSend);
        return "/admin/email/spam";
    }

    @GetMapping("/send")
    public String sendEmails(Model model){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<Email> email_list = getAllEmail();
        if(email_list==null)
            return "/admin/upload/email-api";
        int numOfNormal = 0, numOfSpam = 0, numOfSend = 0;

        for(Email email : email_list){
            if(email.getStatus() == -1){
                continue;
            }
            if(email.getMark() == 0){
                numOfNormal++;
            }else if(email.getMark() == 1){
                numOfSpam++;
            }
        }
        QueryWrapper<Email> wrapper = new QueryWrapper<>();
        wrapper.eq("post_address", user.getEmail());
        wrapper.eq("status", 1);
        wrapper.eq("mark", 2);
        List<Email> list = emailService.list(wrapper);
        numOfSend = list.size();

        model.addAttribute("email_list", list);
        model.addAttribute("hamNum",numOfNormal);
        model.addAttribute("spamNum",numOfSpam);
        model.addAttribute("sendNum",numOfSend);
        return "/admin/email/send";
    }



}
